package com.feng.controller;

import com.feng.dao.NewsDao;
import com.feng.dao.ProductDao;
import com.feng.dto.NewsDto;
import com.feng.dto.ProductDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: 丰
 * @date: 2023/1/31 18:33
 */
@Component
public class AddTask {


    @Autowired
    private NewsDao newsDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 两分钟刷一次
    @Scheduled(cron = "0 0/2 * * * *")
    public void tasks(){
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Thread.currentThread().setName("saveVisits");
        Set<String> keys = redisTemplate.keys("*");

        // product
        List<String> productVisits = keys.stream().filter((key) -> {
            return key.startsWith("productVisits");
        }).collect(Collectors.toList());
        productVisits.forEach((productVisit) -> {
            String id = productVisit.split("\\.")[1];
            Object visits = opsForValue.get("productVisits." + id);
            ProductDto productDto = new ProductDto();
            productDto.setVisits(visits);
            productDto.setId(Integer.parseInt(id));
            productDao.saveVisits(productDto);
        });

        // news
        List<String> newsVisits = keys.stream().filter((key) -> {
            return key.startsWith("newsVisits");
        }).collect(Collectors.toList());
        newsVisits.forEach((newsVisit) -> {
            String id = newsVisit.split("\\.")[1];
            Object visits = opsForValue.get("newsVisits." + id);
            NewsDto newsDto = new NewsDto();
            newsDto.setVisits(visits);
            newsDto.setId(Integer.parseInt(id));
            newsDao.saveVisits(newsDto);
        });
    }
}
